package com.infinit.selfhelp.common.net.converter

import com.google.gson.GsonBuilder
import org.json.JSONArray
import org.json.JSONObject
import java.lang.reflect.Type

class GsonConverter : JSONConvert(code = "errorCode", message = "errorMsg") {
    companion object {
        private val gson = GsonBuilder().registerTypeAdapter(String::class.java, StringConverter()).create()
    }

    override fun <R> String.parseBody(succeed: Type): R? {
//        val string = try {
//            JSONObject(this).getString("resdata")
//        } catch (e: Exception) {
//            this
//        }
//        return gson.fromJson<R>(string, succeed)
        val string = try {
            JSONObject(this).opt("resdata") // 使用 opt 方法获取字段，避免抛出异常
        } catch (e: Exception) {
            this
        }

        return when (string) {
            is String -> gson.fromJson(string, succeed)
            is JSONObject -> gson.fromJson(string.toString(), succeed)
            is Boolean -> string as R
            is JSONArray -> gson.fromJson(string.toString(), succeed)
            else -> null // 其他情况返回 null
        }
    }
}
